package com.quiz.bis.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.quiz.bis.domain.model.QuestionType;
import com.quiz.bis.generate.QuestionDataGenerator;
import com.quiz.bis.generate.QuestionGenerateConfig;
import com.quiz.bis.generate.QuestionGenerateResultVo;
import com.quiz.bis.mapper.QuestionTypeMapper;
import com.quiz.common.core.domain.R;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 题目数据生成器
 * @author ahuan
 */
@Tag(name = "题目数据生成器")
@RestController
@RequestMapping("/questions2/generator")
public class QuestionGeneratorController {

    @Autowired
    private QuestionTypeMapper questionTypeMapper;

    @Autowired
    private QuestionDataGenerator questionDataGenerator;

    /**
     * 获取所有题型
     * @return
     */
    @GetMapping("/types")
    public R<List<QuestionType>> listAllQuestionTypes() {
        List<QuestionType> types = questionTypeMapper.selectList(new QueryWrapper<QuestionType>()
                .eq("del_flag", 0)
                .orderByAsc("sort"));
        return R.ok(types);
    }

    /**
     * 生成题目
     * @param config
     * @return
     */
    @PostMapping("/generate")
    public R<QuestionGenerateResultVo> generateQuestions(@RequestBody QuestionGenerateConfig config) {
        try {
            // 验证题型是否存在
            List<QuestionType> allTypes = questionTypeMapper.selectList();
            Map<String, QuestionType> typeMap = allTypes.stream()
                    .collect(Collectors.toMap(QuestionType::getCode, t -> t));

            for (String typeCode : config.getQuestionCounts().keySet()) {
                if (!typeMap.containsKey(typeCode)) {
                    return R.fail("题型编码不存在: " + typeCode);
                }
            }

            // 验证难度分布
            if (config.getDifficultyDistribution().size() != 5) {
                return R.fail("难度分布必须包含5个值");
            }

            int sum = config.getDifficultyDistribution().stream().mapToInt(Integer::intValue).sum();
            if (sum != 100) {
                return R.fail("难度分布总和必须等于100%");
            }

            // 执行生成
            QuestionGenerateResultVo result = questionDataGenerator.generate(config);
            return R.ok(result);
        } catch (Exception e) {
            return R.fail("生成数据失败: " + e.getMessage());
        }
    }
}